<template>
  <div class="app-container">
    <el-form :model="queryParams" highlight-current-row ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="属性名称" prop="whoBelongsId">
        <el-input
          v-model="queryParams.whoBelongsId"
          placeholder="请输入属性名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="属性唯一标识符" prop="whoBelongs">
        <el-input
          v-model="queryParams.whoBelongs"
          placeholder="请输入属性唯一标识符"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dev:metadata:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dev:metadata:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dev:metadata:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dev:metadata:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="metaDataPropertiesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="属性名称" align="center" prop="name" />
      <el-table-column label="属性标识" align="center" prop="identifier" />
      <el-table-column label="属性读写类型" align="center" prop="accessMode" />
      <el-table-column label="是否是标准功能的必选属性" align="center" prop="required" />
      <el-table-column label="数据类型" align="center" prop="dataType.type" />
      <el-table-column label="数据定义" align="center" prop="dataType.type" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dev:metadata:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dev:metadata:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物模型信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="620px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="属性唯一标识符" prop="identifier">
          <el-input v-model="form.identifier" placeholder="请输入属性唯一标识符" />
        </el-form-item>
        <el-form-item label="属性名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入属性名称" />
        </el-form-item>
        <el-form-item label="属性读写类型" prop="accessMode">
          <el-select v-model="form.accessMode" placeholder="请选择属性读写类型" clearable>
            <el-option
              v-for="dict in dict.type.read_write_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="属性类型"  prop="dataTypeType" >
          <el-select v-model="form.dataType.type" placeholder="请选择属性类型" clearable @change="typeChange">
            <el-option
              v-for="dict in dict.type.data_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <!------------------------------------------------根据属性类型不同输出不同表单--------------------------------->
        <!-- 参数最小值（int、float、double类型特有）-->
        <el-form-item label="参数最小值" prop="min" v-if="this.type == 'int'|| this.type == 'long'">
          <el-input v-model="form.dataType.specs.min" placeholder="请输入参数最小值" />
        </el-form-item>
        <!-- 参数最大值（int、float、double类型特有）-->
        <el-form-item label="参数最大值" prop="max" v-if="this.type == 'int'|| this.type == 'long'">
          <el-input v-model="form.dataType.specs.max" placeholder="请输入参数最大值" />
        </el-form-item>
        <!-- 属性单位（int、float、double类型特有，非必填）-->
        <el-form-item label="属性单位" prop="unit" v-if="this.type == 'int'|| this.type == 'float'|| this.type == 'double'">
          <el-input v-model="form.dataType.specs.unit" placeholder="请输入属性单位" />
        </el-form-item>
        <!-- 单位名称（int、float、double类型特有，非必填）-->
        <el-form-item label="单位名称" prop="unitName" v-if="this.type == 'int'|| this.type == 'float'|| this.type == 'double'">
          <el-input v-model="form.dataType.specs.unitName" placeholder="请输入单位名称" />
        </el-form-item>
        <!--bool类型特有-->
        <el-form-item label="布尔值" prop="bool" v-if="type == 'boolean'">
          <div class="input-box">
            <el-input  v-model="form.dataType.specs.trueText" placeholder="请输入布尔值" value="是" /><span style="margin: 0px 10px">~</span>
            <el-input  v-model="form.dataType.specs.trueValue" placeholder="请输入布尔值" value="true" />
          </div>
          <div class="input-box">
            <el-input v-model="form.dataType.specs.falseText" placeholder="请输入布尔值" value="否" /> <span style="margin: 0px 10px">~</span>
            <el-input v-model="form.dataType.specs.falseValue" placeholder="请输入布尔值" value="false" />
          </div>
        </el-form-item>
        <!-- 数据长度，最大10240（text类型特有）-->
        <el-form-item label="最大长度" prop="text" v-if="this.type == 'text'">
          <el-input v-model="form.dataType.specs.length" placeholder="请输入最大数据长度,最大10240" />
        </el-form-item>
        <!-- 时间格式-->
        <el-form-item label="时间格式" prop="maxLength" v-if="type == 'date'">
          <el-input v-model="form.dataType.specs.timeFormat" placeholder="请输入时间格式" />
        </el-form-item>
        <!--枚举-->
        <el-form-item label="枚举项" prop="enum" v-if="type == 'enum'">
          <div class="input-box" v-for="(item, index) in form.dataType.specs.enumdata" :key="index">
            <el-input v-model="item.text" placeholder="请输入枚举值" />
            <span style="margin: 0px 10px"><i class="el-icon-right"></i></span>
            <el-input v-model="item.value" placeholder="请输入枚举文本" />
            <div class="input-option">
              <span style="margin: 0px 10px" @click="addEnum()" v-if="index == 0"><i class="el-icon-plus"></i></span>
              <span style="margin: 0px 10px" @click="delEnum()" v-if="index != 0"><i class="el-icon-minus"></i></span>
            </div>
          </div>
        </el-form-item>
        <!-- 数组格式-->
        <el-form-item label="数组元素类型" prop="maxLength" v-if="type == 'array'">
          <el-input v-model="form.dataType.specs.arrayType" placeholder="请输入数组元素类型" />
        </el-form-item>
        <!-- 文件类型-->
        <el-form-item label="文件类型" prop="fileType" v-if="type == 'file'">
          <el-select v-model="form.dataType.specs.fileType" placeholder="请选择文件类型" clearable>
            <el-option
              v-for="dict in dict.type.file_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/dev/product";
import { listMetadata, getMetadata, delMetadata, addMetadata, updateMetadata } from "@/api/dev/metadata";
import { addEitTsl,addTsl,updateTsl,removeTsl } from "@/api/dev/tsl";
import { listProperties, getProperties, delProperties, addProperties, updateProperties } from "@/api/dev/product/tabs/properties";

export default {
  name: "properties",
  props: ['id'],
  dicts: ['read_write_type','data_type','file_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物模型信息表格数据
      metadataList: [],
      //物模型信息
      metaData: [],
      // 物模型的属性信息列表
      metaDataPropertiesList:[],
      // 物模型的属性信息 (新增编辑用)
      //metaDataProperties:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        metadata: null,
        whoBelongsId: null,
        whoBelongs: null,
        open: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null
      },
      // 表单参数
      form: {
        identifier: null,
        name: null,
        accessMode: null,
        required: null,
        dataType: {
          type: null,
          specs: {
            min: null,
            max: null,
            unit: null,
            unitName: null,
            size: null,
            step: null,
            length: null,
            //时间格式
            timeFormat:null,
            //数组类型
            arrayType:null,
            //文件类型
            fileType:null,
            trueText: null,
            trueValue: null,
            falseText: null,
            falseValue: null,
            enumdata: [
              {
                text: '',
                value: '',
              },
            ],
            item: {
              type: null
            }
          },
        },
      },
      //相关参数显示隐藏
      type:"",
      // 表单校验
      rules: {
        identifier: [
          { required: true, message: "属性唯一标识符不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "属性名称不能为空", trigger: "blur" },
        ],
        accessMode: [
          { required: true, message: "属性读写类型不能为空", trigger: "change" },
        ],
        // dataTypeType: [
        //   { required: true, message: "属性类型不能为空", trigger: "change" },
        // ],

      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物模型信息列表 */
    getList() {
      this.loading = true;
      //得到该物模型的properties
      getMetadata(this.id).then(response => {
        this.metaData = JSON.parse(response.data.metadata);
        this.metaDataPropertiesList =this.metaData ==null?null : this.metaData.properties;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        identifier: null,
        name: null,
        accessMode: null,
        required: null,
        dataType: {
          type: null,
          specs: {
            min: null,
            max: null,
            unit: null,
            unitName: null,
            size: null,
            step: null,
            length: null,
            //时间格式
            timeFormat:null,
            trueText: null,
            trueValue: null,
            falseText: null,
            falseValue: null,
            enumdata: [
              {
                text: '',
                value: '',
              },
            ],
            item: {
              type: null
            }
          },
        },
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物模型信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMetadata(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物模型信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let req = {
        //属于谁（0-产品，1-设备）
        whoBelongs:0,
        //属于产品或设备的id
        whoBelongsId:1,
        //类型 "properties"--属性 "events"--事件 "services"--服务 "outputData"--参数
        type:"properties",
        //this.form转成String的参数
        param:JSON.stringify(this.form)
      }
      this.$refs["form"].validate(valid => {
        addEitTsl(req).then(response => {
          this.$modal.msgSuccess("成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物模型信息编号为"' + ids + '"的数据项？').then(function() {
        return delMetadata(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dev/metadata/export', {
        ...this.queryParams
      }, `metadata_${new Date().getTime()}.xlsx`)
    },
    typeChange(val){
      console.log(val);
      this.type = val;
    },
    //添加枚举
    addEnum(){
      this.form.dataType.specs.enumdata.push({
        text: '',
        value: '',
      });
    },
    //删除枚举
    delEnum(index){
      this.form.dataType.specs.enumdata.splice(index, 1);
    }
  }
};
</script>
<style>
.input-box {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-top: 10px;
}
.input-option {
  line-height: 30px;
  padding-top: 5px;
  width: 140px;
}
.input-option i {
  margin: 0px 5px;
  border: 1px solid #c3c3c3;
  font-size: 16px;
}
.input-options {
  display: flex;
  align-items: center;
  color: #409eff;
  cursor: pointer;
}
</style>
